package xin.nick.demo.interceptor;

import xin.nick.summer.annotation.Component;
import xin.nick.summer.annotation.Security;
import xin.nick.summer.interceptor.SummerInterceptor;
import xin.nick.summer.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Nick
 * @date 2021/5/30
 * @description 权限拦截器
 */
@Component
public class SecurityInterceptor implements SummerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Handler handler) {

        try {
            // 如果没有权限注解,则直接放行
            if (!handler.getMethod().isAnnotationPresent(Security.class)) {
                return true;
            }

            // 拿到前端传过来的用户名
            String username = request.getParameter("username");

            // 拿到注解里面的权限验证的用户名
            Security security = handler.getMethod().getAnnotation(Security.class);
            // 匹配用户名, 存在则放行,否则不放行
            String[] names = security.value();
            for (String name : names) {
                if(name.equals(username)) {
                    return true;
                }
            }
            String resultString = "没有权限哦";
            if(username != null && username != "") {
                resultString = username + ",你" + resultString;
            }
            response.getWriter().write(resultString);
            return false;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
